extends Node
const FREQ_MAX = 11050.0
const MIN_DB = 60
var spectrum

var _energys=[]# 保存最后2秒的energy
var energy=1
var smoothEnergy=1
var scale1=1

func _ready():
	spectrum = AudioServer.get_bus_effect_instance(0,0)
	
	pass # Replace with function body.


func _process(delta):
	var magnitude: float = spectrum.get_magnitude_for_frequency_range(0, FREQ_MAX).length()
	var e = clamp((MIN_DB + linear2db(magnitude)) / MIN_DB, 0, 1)
	
	
	_energys.append(e)
	if _energys.size()>120:
		_energys.pop_front()
	_updateEnergy()
	_updateSmoothEnergy()
	_updateScale1()

func _updateEnergy():
	if _energys.size()==0:
		energy=1

	var minEnergy=1
	var maxEnergy=0
	var curEnergy=_energys[_energys.size()-1]
	for energy in _energys:
		minEnergy=min(energy,minEnergy)
		maxEnergy=max(energy,maxEnergy)
	if maxEnergy==minEnergy:
		energy=1
	else:
		energy=float(curEnergy-minEnergy)/(maxEnergy-minEnergy)+1
	
func _updateSmoothEnergy():
	if energy>smoothEnergy:
		smoothEnergy=lerp(smoothEnergy,energy,0.5)
	elif energy<smoothEnergy:
		smoothEnergy=lerp(smoothEnergy,energy,0.2)
	pass
func _updateScale1():
	var e=smoothEnergy
	var s=1
	if e<=0.5:
		s=e+0.5
	else:
		s=(e-0.5)*2+0.5
	scale1=s
